<?php
/**
 * Created by PhpStorm.
 * User: zhangbing
 * Date: 2017/5/20
 * Time: 16:16
 */
namespace app\api\controller;
use app\models\Models;
use think\Controller;

class Base extends Controller{
    /**
     * 登录验证
     * @param array $sign
     * @return array
     */
    protected function checkLogin($sign = []){
        $post  = input('param.');
        $rsa   = new \app\service\Rsa();
        $redis = new \app\service\Redis();
        // 签名验证
        self::sign($post,$sign);
        // 获取解密后的数据
        $decrypt = $rsa->decrypt($post['equipment'],$post['encrypt']);
        if(!$decrypt['token']){
            throw new \LogicException('token不能为空',1013);
        }
        // 验证token
        $token = $redis->get($decrypt['token']);
        if(!$token){
            throw new \LogicException('token失效',1011);
        }
        // 根据token获取用户id,并返回
        $uid = $redis->get($decrypt['token']);
        $decrypt['uid'] = $uid;
        // 判断账号状态
        $info = self::getUserInfo($uid);
        if($info['status'] != Models::STATUS_ON){
            throw new \LogicException('该账号已锁定',1014);
        }
        // 判断是否异地登录
        $equipment = $redis->get($uid);
        if($equipment != $post['equipment']){
            //删除token
            $redis->del($decrypt['token']);
            throw new \LogicException('您已在其他设备登录',1015);
        }
        // 更新用户最后请求时间
        self::updateRequestTime($uid);
        // 返回组合数据
        unset($post['equipment'],$post['encrypt']);
        return array_merge($decrypt,$post);
    }

    /**
     * ajax成功返回
     * @param string $data
     * @return array
     */
    protected static function formatSuccessResult($data = null){
        return self::formatResult(0, 'success', $data);
    }

    /**
     * ajax失败返回
     * @param $code
     * @param $errorMsg
     * @param string $data
     * @return array
     */
    protected static function formatResult($code, $errorMsg, $data = null){
        return array('code' => $code,'msg' => $errorMsg,'data'=>$data);
    }

    /**
     * 生成token
     * @param $equipment
     * @param $mobile
     * @param $password
     * @return string
     */
    protected static function setToken($equipment,$mobile,$password){
        return md5(md5($equipment).md5($mobile).md5($password ));
    }

    /**
     * 获取配置文件
     * @return array
     */
    protected function getConfig(){
        $list = db('config')->select();
        $config = [];
        if(!empty($list)){
            foreach($list as $v){
                $config[$v['key']] = $v['value'];
            }
        }
        return $config;
    }

    /**
     * 获取用户信息
     * @param $where array|int(pk)
     * @return array|false|\PDOStatement|string|\think\Model
     */
    protected function getUserInfo($where){
        return is_array($where) ? db('user')->where($where)->find() : db('user')->find($where);
    }

    /**
     * 获取参数
     * @param array $sign
     * @return array
     */
    protected function paramsSign($sign = []){
        $post = input('param.');
        // 签名验证
        self::sign($post,$sign);
        $rsa = new \app\service\Rsa();
        // 获取解密后的数据
        $decrypt = $rsa->decrypt($post['equipment'],$post['encrypt']);
        // 返回组合数据
        unset($post['equipment']);
        unset($post['encrypt']);
        return array_merge($decrypt,$post);
    }

    /**
     * 签名验证
     * @param array $post
     * @param array $sign
     */
    protected function sign($post = [],$sign = []){
        if($sign){
            $keys = array_keys($post);
            $vals = array_values($post);
            // 参数验证
            foreach($sign as $v){
                if(!in_array($v,$keys)){
                    throw new \LogicException('参数错误',1000);
                }
            }
            // 判断空值
            if(in_array('',$vals)){
                throw new \LogicException('参数值不能为空',1022);
            }
        }
    }

    /**
     * 更新请求时间
     * @param $uid
     */
    protected function updateRequestTime($uid){
        $bool = db('user')->where(['id'=>$uid])->update(['last_request_time'=>time()]);
        if(!$bool){
            throw new \LogicException('操作失败',1010);
        }
    }

    /**
     * 更新用户位置信息
     * @param $data
     * @param $where
     */
    protected function updateLocation($data,$where){
        $location = new Models('location');
        $info = $location->_find($where);
        if(!$info){
            $bool = $location->_add(array_merge($data,$where));
        } else {
            $bool = $location->_save($data,$where);
        }
        if(false === $bool){
            throw new \LogicException('操作失败',1010);
        }
    }

    /**
     * 用户详细信息
     * @param $params
     * @return mixed
     */
    public function getUserDetail($params){
        $user = new Models('user');
        // 用户点击数+1
        $bool = $user->_setInc(['id'=>$params['uid']],'click_num');
        if(!$bool){
            throw new \LogicException('操作失败',1010);
        }
        // 获取用户信息
        $join  = [['location c','a.id = c.uid','left']];
        $field = 'a.id,a.nickname,a.birth,a.signature,(a.follow_user_num+a.follow_business_num) follow_num,a.fans_num,a.wine,a.address,a.portrait,sum(a.click_num+a.fans_num) hot';
        $info = $user->joinOne($join,['a.id'=>$params['uid']],$field);
        $info['portrait'] = empty($info['user']['portrait']) ? '' : self::arrayMapPortrait($info['user']['portrait']);
        $info['age']      = calcAge($info['user']['birth']);
        unset($info['birth']);
        return $info;
    }

    /**
     * 查询是否扫码，扫码是否有效
     * @return array
     */
    public function isScan(){
        $scan = new Models('scan');
        return $scan->joinMany([['business b','a.bid = b.id','left']],['a.status'=>Models::SCAN_YES],'a.uid,b.name,b.background');
    }

    /**
     * 获取桌子信息
     * @param $table_id
     * @return array|false|\PDOStatement|string|\think\Model
     */
    function getTableInfo($table_id){
        $table = new Models('table');
        return $table->joinOne([['table_type b','a.type_id = b.id','left']],['a.id'=>$table_id],'b.lowest_cost,a.status,a.is_reserve,b.people_min,b.people_max,b.bid');
    }

    /**
     * 数组映射组合头像图片url
     * @param $image
     * @return string
     */
    function arrayMapPortrait($image){
        $config = self::getConfig();
        return [
            'ori'=>$config['http'].$_SERVER['HTTP_HOST']. DS .'uploads'. DS .'portrait'. DS .$image,
            'thumb'=>$config['http'].$_SERVER['HTTP_HOST']. DS .'uploads'. DS .'portrait'. DS .'s'.$image
        ];
    }

    /**
     * 数组映射组合动态图片url
     * @param $image
     * @return string
     */
    function arrayMapDynamic($image){
        $config = self::getConfig();
        return [
            'ori'=>$config['http'].$_SERVER['HTTP_HOST']. DS .'uploads'. DS .'dynamic'. DS .$image,
            'thumb'=>$config['http'].$_SERVER['HTTP_HOST']. DS .'uploads'. DS .'dynamic'. DS .'s'.$image
        ];
    }

    /**
     * 数组映射组合背景图片url
     * @param $image
     * @return string
     */
    function arrayMapBackground($image){
        $config = self::getConfig();
        return [
            'ori'=>$config['http'].$_SERVER['HTTP_HOST']. DS .'uploads'. DS .'background'. DS .$image,
            'thumb'=>$config['http'].$_SERVER['HTTP_HOST']. DS .'uploads'. DS .'background'. DS .'s'.$image
        ];
    }

    /**
     * 数组映射组合活动图片url
     * @param $image
     * @return string
     */
    function arrayMapActivity($image){
        $config = self::getConfig();
        return [
            'ori'=>$config['http'].$_SERVER['HTTP_HOST']. DS .'uploads'. DS .'activity'. DS .$image,
            'thumb'=>$config['http'].$_SERVER['HTTP_HOST']. DS .'uploads'. DS .'activity'. DS .'s'.$image
        ];
    }

    /**
     * 数组映射组合现场图片url
     * @param $image
     * @return string
     */
    function arrayMapLive($image){
        $config = self::getConfig();
        return [
            'ori'=>$config['http'].$_SERVER['HTTP_HOST']. DS .'uploads'. DS .'live'. DS .$image,
            'thumb'=>$config['http'].$_SERVER['HTTP_HOST']. DS .'uploads'. DS .'live'. DS .'s'.$image
        ];
    }

    /**
     * 数组映射组合现场视频url
     * @param $image
     * @return string
     */
    function arrayMapVideo($image){
        $config = self::getConfig();
        return $config['http'].$_SERVER['HTTP_HOST']. DS .'uploads'. DS .'video'. DS .$image;
    }

    /**
     * 数组映射组合商品图片url
     * @param $image
     * @return string
     */
    function arrayMapGoods($image){
        $config = self::getConfig();
        return [
            'ori'=>$config['http'].$_SERVER['HTTP_HOST']. DS .'uploads'. DS .'goods'. DS .$image,
            'thumb'=>$config['http'].$_SERVER['HTTP_HOST']. DS .'uploads'. DS .'goods'. DS .'s'.$image
        ];
    }
}